package frame.options.sdn;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.util.List;

import javax.swing.ImageIcon;
import javax.swing.JMenuItem;

import model.components.networks.sdn.SdnNetwork;
import frame.SimulatorFrame;
import frame.networks.tables.NetworksTableTabbedPane;
import frame.networks.tables.sdn.SdnTable;
import frame.networks.tables.sdn.SdnTableModel;
import frame.networks.viewers.SdnVisualizationViewersTabbedPane;
import frame.options.sdn.create.CreateSdnWizard;

@SuppressWarnings("serial")
public class CreateSdnMenuItem extends JMenuItem implements ActionListener
{
	private SimulatorFrame simulatorFrame;
	public SimulatorFrame getFrame(){ return simulatorFrame; }
	public void setFrame( SimulatorFrame simulatorFrame ){ this.simulatorFrame = simulatorFrame; }

	public CreateSdnMenuItem( SimulatorFrame simulatorFrame )
	{
		this.setFrame( simulatorFrame );
		
		this.setText( "Create" );
		this.setMnemonic( KeyEvent.VK_C );
		this.setIcon( new ImageIcon( this.getClass().getResource( "/icons/create.png" ) ) );
		this.addActionListener( this );
	}
	
	@Override
	public void actionPerformed( ActionEvent actionEvent )
	{
		NetworksTableTabbedPane networksTableTabbedPane = this.getFrame().getNetworksPanel().getNetworksTablesTabbedPane();
		CreateSdnWizard createSdnWizard = new CreateSdnWizard( this.getFrame() );
		List< SdnNetwork > simulatorPhysicalNetworks = this.getFrame().getSimulator().getSdnNetworks();
		SdnVisualizationViewersTabbedPane sdnVisualizationViewersTabbedPane = this.getFrame().getNetworksPanel().getSdnNetworksViewersTabbedPane();
		SdnTable sdnTable = networksTableTabbedPane.getSdnNetworksTable();
		SdnTableModel sdnTableModel = (SdnTableModel) sdnTable.getModel();
		SaveSdnMenuItem saveSdnMenuItem = this.getFrame().getOptions().getSdnMenu().getSaveSdnNetworksMenuItem();
		
		networksTableTabbedPane.setSelectedIndex( 0 );
		
		if( createSdnWizard.showModalDialog() == 0 )
		{	
			simulatorPhysicalNetworks.clear();
			sdnVisualizationViewersTabbedPane.removeAll();
			sdnTable.removeAll();
			
			for( SdnNetwork physicalNetwork: createSdnWizard.getSdnNetworks() )
			{
				simulatorPhysicalNetworks.add( physicalNetwork );
				sdnVisualizationViewersTabbedPane.addSdnNetworkTab( physicalNetwork );
				sdnTableModel.addRow( new Object[]{ physicalNetwork.getName(), physicalNetwork.getState() } );
			}
			
			sdnTableModel.refresh();
			
			if( simulatorPhysicalNetworks.size() == 0 )
				saveSdnMenuItem.setEnabled( false );
			else
				saveSdnMenuItem.setEnabled( true );
		}
	}
	
}
